package com.party.mobile.web.controller.information;

import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.information.Information;
import com.party.core.model.information.InformationType;
import com.party.core.model.information.InformationTypeGenre;
import com.party.core.service.information.IInformationService;
import com.party.core.service.information.IInformationTypeService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.information.output.InformationOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @ClassName InformationController
 * @Description
 * @Author shenliuhai
 * @Date 2020/2/6 11:17
 **/
@Controller
@RequestMapping("information")
public class InformationController {

    @Autowired
    private IInformationService informationService;

    @Autowired
    private IInformationTypeService informationTypeService;

    protected static Logger logger = LoggerFactory.getLogger(InformationController.class);

    public static final String TYPE_ALL = "1";

    /**
     * 资讯列表
     *
     * @param cityId
     * @param typeId
     * @param
     * @return com.party.mobile.web.dto.AjaxResult
     * @author shenliuhai
     * @date 2020/2/6 11:22
     */
    @RequestMapping("info/list")
    @ResponseBody
    public AjaxResult getList(String cityId, String typeId, Page page) {
        try {

            Information information = new Information();
            information.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            information.setCityId(cityId);
            Map<String,Object> params = new HashMap<>();
            if (!TYPE_ALL.equals(typeId) && StringUtils.isNotEmpty(typeId)) {
                information.setInformationTypeId(typeId);
            } else {
                //获取普通类型Id
                InformationType type = new InformationType();
                type.setCategory(InformationTypeGenre.INFORMATIONTYPE_CATEGORY_ORDINARY.getCode());
                List<InformationType> list = informationTypeService.list(type);
                List<String> typeIds = LangUtils.transform(list, informationType -> {
                    return informationType.getId();
                });
                params.put("typeIds",typeIds);
            }

            List<Information> list = informationService.mobileListPage(information, params, page);

            List<InformationOutput> outputs = LangUtils.transform(list, input -> {
                InformationOutput output = InformationOutput.transform(input);

                Date createDate = input.getCreateDate();
                String diff = DateUtils.getDateDiff(createDate);
                output.setTimeBefore(diff);

                return output;
            });

            return AjaxResult.success(outputs, page);
        } catch (Exception e) {
            logger.error("获取资讯列表失败", e);
            e.printStackTrace();
            return AjaxResult.error(500, "获取资讯列表失败");
        }
    }

    /**
     * 资讯详情
     *
     * @param id
     * @return com.party.mobile.web.dto.AjaxResult
     * @author shenliuhai
     * @date 2020/2/6 11:26
     */
    @RequestMapping("details")
    @ResponseBody
    public AjaxResult details(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数为空");
            }

            Information information = informationService.get(id);

            if (null == information || null == information.getContent()
                    || information.getDelFlag().equals("1")) {
                return AjaxResult.error(PartyCode.IS_NO_DATA, "资讯内容不存在");
            }

            InformationOutput output = InformationOutput.transform(information);
            //设置文章内容
            output.setContent(StringUtils.unescapeHtml4Video2Iframe(information.getContent()));

            Integer readNum = information.getReadNum() == null ? 0 : information.getReadNum();
            //更新阅读数
            information.setReadNum(readNum + 1);
            informationService.update(information);

            return AjaxResult.success(output);
        } catch (Exception e) {
            logger.error("查看资讯详情失败", e);
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 资讯类型
     *
     * @param
     * @return com.party.mobile.web.dto.AjaxResult
     * @author shenliuhai
     * @date 2020/2/6 11:27
     */
    @RequestMapping("typeList")
    @ResponseBody
    public AjaxResult typeList() {
        try {
            InformationType informationType = new InformationType();
            informationType.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            informationType.setCategory(InformationTypeGenre.INFORMATIONTYPE_CATEGORY_ORDINARY.getCode());
            List<InformationType> typeList = informationTypeService.list(informationType);

            //固定一条‘全部’类型
            informationType.setName("全部");
            informationType.setSort(0);
            informationType.setId("1");
            List<InformationType> list = new ArrayList<>();
            list.add(informationType);
            list.addAll(typeList);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("获取资讯分类失败", e);
            e.printStackTrace();
            return AjaxResult.error();
        }
    }


    /**
     * 海报列表
     *
     * @param cityId
     * @param typeId
     * @return com.party.mobile.web.dto.AjaxResult
     * @author shenliuhai
     * @date 2020/2/6 11:27
     */
    @RequestMapping("posterList")
    @ResponseBody
    public AjaxResult posterList(String cityId, String typeId) {
        try {

            Information information = new Information();
            information.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            Map<String,Object> params = new HashMap<>();
            information.setCityId(cityId);
            if (StringUtils.isNotEmpty(typeId) && !TYPE_ALL.equals(typeId)) {
                information.setInformationTypeId(typeId);
            } else {
                //获取普通类型Id
                InformationType type = new InformationType();
                type.setCategory(InformationTypeGenre.INFORMATIONTYPE_CATEGORY_ORDINARY.getCode());
                List<InformationType> list = informationTypeService.list(type);
                List<String> typeIds = LangUtils.transform(list, informationType -> {
                    return informationType.getId();
                });
                params.put("typeIds",typeIds);
            }
            List<Information> list = informationService.mobileListPage(information,params,null);

            //只获取资讯列表的前三个，做为海报列表
            List<Information> posterList = new ArrayList<>();

            if (list.size() > Integer.valueOf(3)) {
                posterList.add(list.get(0));
                posterList.add(list.get(1));
                posterList.add(list.get(2));
            } else {
                posterList = list;
            }

            return AjaxResult.success(posterList);
        } catch (Exception e) {
            logger.error("获取海报列表失败", e);
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 获取互助和联系模块文章详情
     * @author shenliuhai
     * @date 2020/2/18 14:14
     * @param categoryId
     * @return com.party.mobile.web.dto.AjaxResult
     */
    @RequestMapping("module/details")
    @ResponseBody
    public AjaxResult getModuleDetailsByCode(Integer categoryId) {

        try {
            if (categoryId == null) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数为空");
            }

            InformationType informationType = new InformationType();
            informationType.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            informationType.setCategory(categoryId);

            List<InformationType> list = informationTypeService.list(informationType);
            if (list.size() > 0) {
                InformationType type = list.get(0);

                Information information = new Information();
                information.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                information.setInformationTypeId(type.getId());
                List<Information> informationList = informationService.list(information);

                if (informationList.size() > 0) {
                    Information information1 = informationList.get(0);
                    InformationOutput output = InformationOutput.transform(information1);
                    //设置文章内容
                    output.setContent(StringUtils.unescapeHtml4Video2Iframe(information1.getContent()));

                    Integer readNum = information1.getReadNum() == null ? 0 : information1.getReadNum();
                    //更新阅读数
                    information1.setReadNum(readNum + 1);
                    informationService.update(information1);

                    return AjaxResult.success(output);
                }
                return AjaxResult.error(PartyCode.IS_NO_DATA, "资讯内容不存在");
            }
            return AjaxResult.error(PartyCode.IS_NO_DATA, "类型不存在");
        } catch (Exception e) {
           logger.error("获取互助或联系模块文章详情失败",e);
           return AjaxResult.error();
        }
    }

    @ResponseBody
    @RequestMapping("update/share/num")
    public AjaxResult updateArticleShareNum(String id) {

        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数为空");
            }

            Information information = informationService.get(id);

            Integer shareNum = information.getShareNum() == null ? 0 : information.getShareNum();

            information.setShareNum(shareNum + 1);
            informationService.update(information);
            return AjaxResult.success();

        } catch (Exception e) {
           logger.error("修改资讯分享数失败",e);
           return AjaxResult.error();
        }

    }
}
